package com.fly.socket.sample2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * ServerSocket
 * 
 * @author 00fly
 * @version [版本号, 2020年6月18日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class MyServer
{
    public static void main(String[] args)
    {
        try (ServerSocket server = new ServerSocket(10000))
        {
            while (true)
            {
                Socket socket = server.accept();
                invoke(socket);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * 支持多client
     * 
     * @param client
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    private static void invoke(final Socket client)
        throws IOException
    {
        new Thread(() -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()))
            {
                while (true)
                {
                    String msg = in.readLine();
                    System.out.println(msg);
                    out.println("Server received " + msg);
                    out.flush();
                    if ("bye".equals(msg))
                    {
                        break;
                    }
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }).start();
    }
}